package com.dianrui.fmi.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.EditStockActivity;
import com.dianrui.fmi.activity.KLineActivity;
import com.dianrui.fmi.activity.MessageListActivity;
import com.dianrui.fmi.activity.SearchActivity;
import com.dianrui.fmi.adapter.HomeQuotesAdapter;
import com.dianrui.fmi.adapter.MainGridAdapter;
import com.dianrui.fmi.bean.HomeQutos;
import com.dianrui.fmi.bean.HotSymbols;
import com.dianrui.fmi.bean.Member;
import com.dianrui.fmi.event.RfreshFaq;
import com.dianrui.fmi.event.RfreshIndex;
import com.dianrui.fmi.event.RfreshInfomation;
import com.dianrui.fmi.event.RfreshUnread;
import com.dianrui.fmi.event.SwitchQuotes;
import com.dianrui.fmi.util.BadgerUtils;
import com.dianrui.fmi.util.CountDownTimerUtils;
import com.dianrui.fmi.util.GlideUtil;
import com.dianrui.fmi.util.MyDataSetObserver;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.HorizontalListViewNew;
import com.dianrui.fmi.view.ResizableImageView;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshScrollView;
import com.google.gson.JsonObject;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;


public class HomeFragment extends BaseFragment {
    private List<String> topimgIdArray = new ArrayList<>();
    private List<String> toptitlesArray = new ArrayList<>();
    private List<String> topurlArray = new ArrayList<>();
    private ImageView[] topimageViews;
    private ImageView topimageView;
    private int currentPosition=0;

    private String type;
    // 轮播图的数组
    private ImageView[] imageViews;

    private List<HomeQutos> mHomeQutoList = new ArrayList<>();
    private List<Member> memberList = new ArrayList<>();
    private List<HotSymbols> mHotSymbolsList = new ArrayList<>();
    private HomeQuotesAdapter homeQuotesAdapter;
    private MainGridAdapter mainGridAdapter;
    private boolean isStop = false;
    private boolean isAuto=true;
    private List<Fragment> fragments;
    private List<String> titles;
    private int flag = 0;

    @BindView(R.id.notice_flipper)
    ViewFlipper viewFlipper;
    @BindView(R.id.main_stock_list)
    ListView mainStockList;
    @BindView(R.id.god_gridview)
    HorizontalListViewNew godGridview;
    @BindView(R.id.currency_txt)
    TextView currencyTxt;
    @BindView(R.id.main_currency_line)
    View mainCurrencyLine;
    @BindView(R.id.commody_txt)
    TextView commodyTxt;
    @BindView(R.id.main_commody_line)
    View mainCommodyLine;
    @BindView(R.id.act_my_msg_num)
    TextView actMyMsgNum;
    @BindView(R.id.viewpager)
    ViewPager topViewpager;
    @BindView(R.id.top_viewGroup)
    LinearLayout topViewGroup;
    @BindView(R.id.pager)
    ViewPager pager;

    @BindView(R.id.tablayout)
    TabLayout tablayout;

    @BindView(R.id.my_scrollview)
    PullToRefreshScrollView pullToRefreshScrollView;

    @BindView(R.id.home_emptyView)
    LinearLayout homeEmptyView;

    @BindView(R.id.add_stock_btn)
    Button addStock;



    @Override
    public int getContentViewId() {
        return R.layout.frag_home;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        homeQuotesAdapter = new HomeQuotesAdapter(getActivity(), mHomeQutoList);
        mainStockList.setAdapter(homeQuotesAdapter);
        homeQuotesAdapter.registerDataSetObserver(new MyDataSetObserver(mainStockList));
        type = "0";
        getTopAd();
        getHotSymbols();
        getUnreadNumber();
        getForex();
        loadBottomTab();
        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                switch (type) {
                    case "0":
                        getForex();
                        break;

                    case "1":
                        getCommodities();
                        break;

                    default:
                        break;
                }
                getUnreadNumber();
                getHotSymbols();
                EventBus.getDefault().post(new RfreshFaq());
                EventBus.getDefault().post(new RfreshInfomation());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                switch (type) {
                    case "0":
                        getForex();

                        break;
                    case "1":
                        getCommodities();
                        break;
                    default:
                        break;
                }
                getUnreadNumber();
                getHotSymbols();
                EventBus.getDefault().post(new RfreshFaq());
                EventBus.getDefault().post(new RfreshInfomation());
            }
        });

        homeQuotesAdapter.setOnButtonClickListener(new HomeQuotesAdapter.QuotesClickListener() {
            @Override
            public void onRegularClick(long tick, String name, String symbold, String type, String symbol, String fullsymbol, String price, String high, String low, String open, String zf, String yc, String buy1, String buy2, String position, String servicecharge, String zc) {
                Intent intent = new Intent(getActivity(), KLineActivity.class);
                Bundle bundle = new Bundle();
                bundle.putLong("tick", tick);
                bundle.putString("symbold", symbold);
                bundle.putString("name", name);
                bundle.putString("type", type);
                bundle.putString("symbol", symbol);
                bundle.putString("open", open);
                bundle.putString("high", high);
                bundle.putString("low", low);
                bundle.putString("fullsymbol", fullsymbol);
                bundle.putString("price", price);
                bundle.putString("zf", zf);
                bundle.putString("type", "1");
                bundle.putString("zc", zc);
                bundle.putString("yc", yc);
                bundle.putString("buy1", buy1);
                bundle.putString("buy2", buy2);
                bundle.putString("position", position);
                bundle.putString("servicecharge", servicecharge);
                intent.putExtras(bundle);
                startActivity(intent);
            }

        });
        detailsTimer.start();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshUnread rfreshUnread) {
        getUnreadNumber();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshIndex rfreshIndex) {
        getForex();
        getCommodities();
    }

    private void getHotSymbols() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.INDEX, "", new   OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("hot_symbols");
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    for (int i = 0; i <jsonArray.length() ; i++) {
                                        final JSONObject content = new JSONObject(jsonArray.opt(i).toString());
                                        HotSymbols hotSymbols = new HotSymbols();
                                        hotSymbols.symbols_id = jsonArray.optJSONObject(i).optString("symbols_id");
                                        hotSymbols.full_symbol = jsonArray.optJSONObject(i).optString("full_symbol");
                                        hotSymbols.symbol = jsonArray.optJSONObject(i).optString("symbol");
                                        hotSymbols.name = jsonArray.optJSONObject(i).optString("name");
                                        hotSymbols.type = jsonArray.optJSONObject(i).optString("type");
                                        hotSymbols.market = jsonArray.optJSONObject(i).optString("market");
                                        hotSymbols.tick = jsonArray.optJSONObject(i).optLong("tick");
                                        hotSymbols.i = jsonArray.optJSONObject(i).optString("i");
                                        hotSymbols.itd = jsonArray.optJSONObject(i).optString("itd");
                                        hotSymbols.price = jsonArray.optJSONObject(i).optString("price");
                                        hotSymbols.o = jsonArray.optJSONObject(i).optString("o");
                                        hotSymbols.h = jsonArray.optJSONObject(i).optString("h");
                                        hotSymbols.l = jsonArray.optJSONObject(i).optString("l");
                                        hotSymbols.yc = jsonArray.optJSONObject(i).optString("yc");
                                        hotSymbols.v = jsonArray.optJSONObject(i).optString("v");
                                        hotSymbols.zf = jsonArray.optJSONObject(i).optString("zf");
                                        hotSymbols.zc = jsonArray.optJSONObject(i).optString("zc");
                                        hotSymbols.zd = jsonArray.optJSONObject(i).optString("zd");
                                        hotSymbols.buy1 = jsonArray.optJSONObject(i).optString("buy1");
                                        hotSymbols.buy2 = jsonArray.optJSONObject(i).optString("buy2");
                                        hotSymbols.position = jsonArray.optJSONObject(i).optString("position");
                                        hotSymbols.service_charge = jsonArray.optJSONObject(i).optString("service_charge");
                                        mHotSymbolsList.add(hotSymbols);
                                        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_viewflipper,null);
                                        TextView viewflipperFullsymbol = view.findViewById(R.id.viewflipper_fullsymbol);
                                        TextView viewflipperzf = view.findViewById(R.id.viewflipper_zf);
                                        TextView viewflipperPrice = view.findViewById(R.id.viewflipper_price);
                                        if (mHotSymbolsList.get(i).zf.contains("-")) {
                                            viewflipperzf.setTextColor(getResources().getColor(R.color.green));
                                            viewflipperPrice.setTextColor(getResources().getColor(R.color.green));
                                        }else {
                                            viewflipperzf.setTextColor(getResources().getColor(R.color.red_deep));
                                            viewflipperPrice.setTextColor(getResources().getColor(R.color.red_deep));
                                        }
                                        viewflipperFullsymbol.setText(mHotSymbolsList.get(i).full_symbol);
                                        viewflipperzf.setText(mHotSymbolsList.get(i).zf);
                                        viewflipperPrice.setText(mHotSymbolsList.get(i).price);
                                        viewFlipper.addView(view);
                                    }
                                    viewFlipper.setAutoStart(true);
                                    viewFlipper.setFlipInterval(6000);
                                    viewFlipper.startFlipping();
                                    viewFlipper.setInAnimation(getActivity(), R.anim.notice_in);
                                    viewFlipper.setOutAnimation(getActivity(), R.anim.notice_out);
                                    viewFlipper.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            int id = viewFlipper.getCurrentView().getId();
                                            int displayedChild = viewFlipper.getDisplayedChild();
                                            if (id == R.id.viewfilpper_layout) {
                                                Intent intent = new Intent(getActivity(), KLineActivity.class);
                                                Bundle bundle = new Bundle();
                                                bundle.putLong("tick", mHotSymbolsList.get(displayedChild).tick);
                                                bundle.putString("symbold", mHotSymbolsList.get(displayedChild).symbols_id);
                                                bundle.putString("name",mHotSymbolsList.get(displayedChild).name);
                                                bundle.putString("type",  mHotSymbolsList.get(displayedChild).type);
                                                bundle.putString("symbol", mHotSymbolsList.get(displayedChild).symbol);
                                                bundle.putString("open", mHotSymbolsList.get(displayedChild).o);
                                                bundle.putString("high", mHotSymbolsList.get(displayedChild).h);
                                                bundle.putString("low", mHotSymbolsList.get(displayedChild).l);
                                                bundle.putString("fullsymbol", mHotSymbolsList.get(displayedChild).full_symbol);
                                                bundle.putString("price", mHotSymbolsList.get(displayedChild).price);
                                                bundle.putString("zf", mHotSymbolsList.get(displayedChild).zf);
                                                bundle.putString("type", "1");
                                                bundle.putString("zc", mHotSymbolsList.get(displayedChild).zc);
                                                bundle.putString("yc", mHotSymbolsList.get(displayedChild).yc);
                                                bundle.putString("buy1", mHotSymbolsList.get(displayedChild).buy1);
                                                bundle.putString("buy2", mHotSymbolsList.get(displayedChild).buy2);
                                                bundle.putString("position", mHotSymbolsList.get(displayedChild).position);
                                                bundle.putString("servicecharge", mHotSymbolsList.get(displayedChild).service_charge);
                                                intent.putExtras(bundle);
                                                startActivity(intent);
                                            }
                                        }
                                    });
                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void getUnreadNumber() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.UNREADNUMBER, "", new OkHttpUtils.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {//1000是成功获取数据
                                    int msgNumber = jsonObject.optJSONObject("data").optInt("unread_number");
                                    if (msgNumber > 0) {
                                        BadgerUtils.addBadger(getActivity(), jsonObject.optJSONObject("data").optInt("unread_number"));
                                        actMyMsgNum.setText(msgNumber + "");
                                        actMyMsgNum.setVisibility(View.VISIBLE);
                                    } else if (msgNumber >= 99) {
                                        actMyMsgNum.setText("+99");
                                        actMyMsgNum.setVisibility(View.VISIBLE);
                                    } else {
                                        BadgerUtils.removeCount(getActivity());//移除角标
                                        actMyMsgNum.setVisibility(View.GONE);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });

    }

    private void getTopAd() {
        if (null != topimgIdArray && topimgIdArray.size() > 0) {
            topimgIdArray.clear();
        }
        if (null != toptitlesArray && toptitlesArray.size() > 0) {
            toptitlesArray.clear();
        }
        if (null != topurlArray && topurlArray.size() > 0) {
            topurlArray.clear();
        }
        OkHttpUtils.getInstance().postWithMemberToken(Url.INDEX, "",  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {

                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.getString("status"))) {
                                if (pullToRefreshScrollView != null) {
                                    pullToRefreshScrollView.onRefreshComplete();
                                }
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("ad_list");
                                final long tipTimes = (jsonObject.optJSONObject("data").getLong("run_time") + 1) * 1000;
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject content = new JSONObject(jsonArray.opt(i).toString());
                                        topimgIdArray.add(content.optString("picture"));
                                        toptitlesArray.add(content.optString("title"));
                                        topurlArray.add(content.optString("link_url"));
                                    }
                                    TopLoadPageAdapter topPageAdapter = new TopLoadPageAdapter();
                                    topViewpager.setAdapter(topPageAdapter);

                                    if (topimgIdArray.size() == 1) {
                                        topViewGroup.setVisibility(View.GONE);
                                    } else {
                                        topViewGroup.setVisibility(View.VISIBLE);
                                        //有多少个界面就new多长的数组
                                        topimageViews = new ImageView[topimgIdArray.size()];
                                        for (int i = 0; i < topimageViews.length; i++) {
                                            //new新的ImageView控件
                                            topimageView = new ImageView(getActivity());
                                            //设置控件的宽高
                                            topimageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
                                            //设置控件的padding属性
                                            topimageView.setPadding(5, 0, 5, 0);
                                            topimageViews[i] = topimageView;
                                            //初始化第一个page页面的图片的原点为选中状态
                                            if (i == 0) {
                                                //表示当前图片
                                                topimageViews[i].setBackgroundResource(R.drawable.red_dot);
                                            } else {
                                                topimageViews[i].setBackgroundResource(R.drawable.white_dot);
                                            }
                                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                                                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                            layoutParams.leftMargin = 5;
                                            layoutParams.rightMargin = 8;
                                            layoutParams.topMargin = 4;
                                            layoutParams.bottomMargin = 26;
                                            // 将imageviews添加到小圆点视图组
                                            topViewGroup.addView(topimageViews[i], layoutParams);

                                        }
                                    }
                                    topViewpager.addOnPageChangeListener(new TopBannerListener());
                                    thread.start();
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


    }

    Thread thread=new Thread(new Runnable() {

        @Override
        public void run() {
            while(isAuto){
                try {
                    Thread.sleep(5000);
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what==0){
                currentPosition ++;
                //如果是自动轮播时，让代表显示页面的指示位置+1;
                topViewpager.setCurrentItem(currentPosition,false);
            }
        }
    };


    class TopBannerListener implements ViewPager.OnPageChangeListener {


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (topimageViews.length > 0) {
                final int newPostion = position % topimgIdArray.size();
                for (int i = 0; i < topimageViews.length; i++) {
                    topimageViews[newPostion].setBackgroundResource(R.drawable.red_dot);
                    if (newPostion != i) {
                        topimageViews[i].setBackgroundResource(R.drawable.white_dot);
                    }
                }

            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }


    private void getForex() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.INDEX, "", new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (pullToRefreshScrollView != null) {
                                    pullToRefreshScrollView.onRefreshComplete();
                                }
                                if (mHomeQutoList != null) {
                                    mHomeQutoList.clear();
                                }
                                JSONArray optionalForex = jsonObject.optJSONObject("data").optJSONArray("optional_forex");
                                if(optionalForex.length()>0){
                                    for (int i = 0; i <optionalForex.length() ; i++) {
                                        HomeQutos homeQutos = new HomeQutos();
                                        homeQutos.symbols_id = optionalForex.optJSONObject(i).optString("symbols_id");
                                        homeQutos.full_symbol = optionalForex.optJSONObject(i).optString("full_symbol");
                                        homeQutos.symbol = optionalForex.optJSONObject(i).optString("symbol");
                                        homeQutos.name = optionalForex.optJSONObject(i).optString("name");
                                        homeQutos.type = optionalForex.optJSONObject(i).optString("type");
                                        homeQutos.market = optionalForex.optJSONObject(i).optString("market");
                                        homeQutos.tick = optionalForex.optJSONObject(i).optLong("tick");
                                        homeQutos.i = optionalForex.optJSONObject(i).optString("i");
                                        homeQutos.itd = optionalForex.optJSONObject(i).optString("itd");
                                        homeQutos.price = optionalForex.optJSONObject(i).optString("price");
                                        homeQutos.o = optionalForex.optJSONObject(i).optString("o");
                                        homeQutos.h = optionalForex.optJSONObject(i).optString("h");
                                        homeQutos.l = optionalForex.optJSONObject(i).optString("l");
                                        homeQutos.yc = optionalForex.optJSONObject(i).optString("yc");
                                        homeQutos.v = optionalForex.optJSONObject(i).optString("v");
                                        homeQutos.zf = optionalForex.optJSONObject(i).optString("zf");
                                        homeQutos.zd = optionalForex.optJSONObject(i).optString("zd");
                                        homeQutos.buy1 = optionalForex.optJSONObject(i).optString("buy1");
                                        homeQutos.buy2 = optionalForex.optJSONObject(i).optString("buy2");
                                        homeQutos.position = optionalForex.optJSONObject(i).optString("position");
                                        homeQutos.service_charge = optionalForex.optJSONObject(i).optString("service_charge");
                                        mHomeQutoList.add(homeQutos);
                                    }
                                    if (homeQuotesAdapter != null) {
                                        homeQuotesAdapter.refresh(mHomeQutoList);
                                    }
                                    mainStockList.setVisibility(View.VISIBLE);
                                    homeEmptyView.setVisibility(View.GONE);

                                }else {
                                    mainStockList.setVisibility(View.INVISIBLE);
                                    homeEmptyView.setVisibility(View.VISIBLE);
                                }
                            } else {
                                pullToRefreshScrollView.onRefreshComplete();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    pullToRefreshScrollView.onRefreshComplete();
                }
            }
        });
    }

    private void getCommodities() {
        JsonObject jsonObject = new JsonObject();
        OkHttpUtils.getInstance().postWithMemberToken(Url.INDEX, "",  new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                pullToRefreshScrollView.onRefreshComplete();
                                if (mHomeQutoList != null) {
                                    mHomeQutoList.clear();
                                }
                                JSONArray optionalCommodities = jsonObject.optJSONObject("data").optJSONArray("optional_commodities");
                                if(optionalCommodities.length()>0){
                                    for (int i = 0; i <optionalCommodities.length() ; i++) {
                                        HomeQutos homeQutos = new HomeQutos();
                                        homeQutos.symbols_id = optionalCommodities.optJSONObject(i).optString("symbols_id");
                                        homeQutos.full_symbol = optionalCommodities.optJSONObject(i).optString("full_symbol");
                                        homeQutos.symbol = optionalCommodities.optJSONObject(i).optString("symbol");
                                        homeQutos.name = optionalCommodities.optJSONObject(i).optString("name");
                                        homeQutos.type = optionalCommodities.optJSONObject(i).optString("type");
                                        homeQutos.market = optionalCommodities.optJSONObject(i).optString("market");
                                        homeQutos.tick = optionalCommodities.optJSONObject(i).optLong("tick");
                                        homeQutos.i = optionalCommodities.optJSONObject(i).optString("i");
                                        homeQutos.itd = optionalCommodities.optJSONObject(i).optString("itd");
                                        homeQutos.price = optionalCommodities.optJSONObject(i).optString("price");
                                        homeQutos.o = optionalCommodities.optJSONObject(i).optString("o");
                                        homeQutos.h = optionalCommodities.optJSONObject(i).optString("h");
                                        homeQutos.l = optionalCommodities.optJSONObject(i).optString("l");
                                        homeQutos.yc = optionalCommodities.optJSONObject(i).optString("yc");
                                        homeQutos.v = optionalCommodities.optJSONObject(i).optString("v");
                                        homeQutos.zf = optionalCommodities.optJSONObject(i).optString("zf");
                                        homeQutos.zd = optionalCommodities.optJSONObject(i).optString("zd");
                                        homeQutos.buy1 = optionalCommodities.optJSONObject(i).optString("buy1");
                                        homeQutos.buy2 = optionalCommodities.optJSONObject(i).optString("buy2");
                                        homeQutos.position = optionalCommodities.optJSONObject(i).optString("position");
                                        homeQutos.service_charge = optionalCommodities.optJSONObject(i).optString("service_charge");
                                        mHomeQutoList.add(homeQutos);
                                    }
                                    if (homeQuotesAdapter != null) {
                                        homeQuotesAdapter.refresh(mHomeQutoList);
                                    }
                                    mainStockList.setVisibility(View.VISIBLE);
                                    homeEmptyView.setVisibility(View.GONE);

                                }else {
                                    mainStockList.setVisibility(View.INVISIBLE);
                                    homeEmptyView.setVisibility(View.VISIBLE);
                                }


                            } else {
                                pullToRefreshScrollView.onRefreshComplete();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    pullToRefreshScrollView.onRefreshComplete();
                }
            }
        });
    }

    CountDownTimerUtils detailsTimer = new CountDownTimerUtils(Long.MAX_VALUE, 5000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getHotSymbols();
            switch (type) {
                case "0":
                    getForex();
                    break;
                case "1":
                    getCommodities();
                    break;
                    default:
                        break;
            }


        }

        @Override
        public void onFinish() {

        }
    };

    private void loadBottomTab() {
        titles = new ArrayList<>();
        titles.add(getString(R.string.strategy_recommendation));
        titles.add(getString(R.string.faq));
        titles.add(getString(R.string.ll));

        fragments = new ArrayList<>();
        fragments.add(new StrategyRecommendationFragment());
        fragments.add(new FaqFragment());
        fragments.add(new ImportantInformationFragment());

        //预加载
        pager.setOffscreenPageLimit(fragments.size());

        //设置适配器
        FragmentManager childFragmentManager = getChildFragmentManager();
        pager.setAdapter(new FragmentPagerAdapter(childFragmentManager) {
            //选中的ITem
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            //返回Item个数
            @Override
            public int getCount() {
                return fragments.size();
            }
            //设置标题

            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });

        tablayout.setupWithViewPager(pager);
    }


    @Override
    public void getData() {}

    class TopLoadPageAdapter extends PagerAdapter {//顶部广告的适配器

        @Override
        public int getCount() {
            if (topimgIdArray == null) {
                return 0;
            }
            if (topimgIdArray.size() == 1) {
                return topimgIdArray.size();
            } else {
                return Integer.MAX_VALUE;//图片有多少张就有多少
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            ResizableImageView imageView = new ResizableImageView(getActivity());
            if (topimgIdArray.size() > 0) {
                final int newPostion = position % topimgIdArray.size();
                GlideUtil.loadImageView(getActivity(), topimgIdArray.get(newPostion), imageView);

            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    @OnClick({R.id.search_layout,R.id.serivce_layout,R.id.last_price_layout, R.id.msg_click_layout, R.id.main_currency_layout, R.id.main_commody_layout, R.id.edit_stuck,R.id.add_stock_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_layout:
                JumpActivitys(SearchActivity.class);
                break;

            case R.id.serivce_layout:
                //JumpActivitys(ChatActivity.class);
                break;

            case R.id.msg_click_layout:
                JumpActivitys(MessageListActivity.class);
                break;
            case R.id.main_currency_layout:
                type = "0";
                currencyTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.orange));
                commodyTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333333));
                mainCurrencyLine.setVisibility(View.VISIBLE);
                mainCommodyLine.setVisibility(View.INVISIBLE);
                getForex();
                break;
            case R.id.main_commody_layout:
                type = "1";
                currencyTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_333333));
                commodyTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.orange));
                mainCurrencyLine.setVisibility(View.INVISIBLE);
                mainCommodyLine.setVisibility(View.VISIBLE);
                getCommodities();
                break;
            case R.id.edit_stuck:
                JumpActivitys(EditStockActivity.class);
                break;

            case R.id.add_stock_btn:
                EventBus.getDefault().post(new SwitchQuotes());
                break;

            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        if (topViewpager != null) {
            topViewpager.removeAllViews();
        }
        EventBus.getDefault().unregister(this);
        isStop=false;
        isAuto=false;
        super.onDestroy();
    }
}
